// SQL工具专用功能
class SQLTool {
    constructor() {
        this.init();
    }

    init() {
        this.bindEvents();
    }

    bindEvents() {
        // 输入方式切换标签
        const inputTabs = document.querySelectorAll('#sql-tool .input-tab');
        inputTabs.forEach(tab => {
            tab.addEventListener('click', (e) => {
                e.preventDefault();
                const tabName = e.target.dataset.tab;
                this.switchInputTab(tabName);
            });
        });
    }

    switchInputTab(tabName) {
        // 更新标签状态
        document.querySelectorAll('#sql-tool .input-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        const targetTab = document.querySelector(`#sql-tool [data-tab="${tabName}"]`);
        if (targetTab) {
            targetTab.classList.add('active');
        }

        // 更新内容区域
        document.querySelectorAll('#sql-tool .input-content').forEach(content => {
            content.classList.remove('active');
        });
        const targetContent = document.getElementById(`${tabName}-input`);
        if (targetContent) {
            targetContent.classList.add('active');
        }
    }

    convertToSql() {
        const inputData = document.getElementById('sql-input-data').value.trim();
        if (!inputData) {
            alert('请输入数据');
            return;
        }

        const dataType = document.getElementById('sql-data-type').value;
        const fieldName = document.getElementById('sql-field-name').value.trim();

        const lines = inputData.split('\n')
            .map(line => line.trim())
            .filter(line => line.length > 0);

        if (lines.length === 0) {
            alert('没有有效的数据');
            return;
        }

        let formattedValues;
        switch (dataType) {
            case 'number':
                // 数字类型：直接使用原字符串，不加任何引号
                formattedValues = lines;
                break;
            case 'string':
                // 字符串单引号：添加单引号，转义内部单引号
                formattedValues = lines.map(line => `'${line.replace(/'/g, "''")}'`);
                break;
            case 'json':
                // 字符串双引号：添加双引号，转义内部双引号
                formattedValues = lines.map(line => `"${line.replace(/"/g, '\\"')}"`);
                break;
            default:
                formattedValues = lines.map(line => `'${line}'`);
        }

        if (formattedValues.length === 0) {
            alert('没有有效的数据');
            return;
        }

        let sqlCondition;
        if (fieldName) {
            sqlCondition = `${fieldName} IN (${formattedValues.join(', ')})`;
        } else {
            // 无字段名时，直接输出值列表，不加括号
            sqlCondition = formattedValues.join(', ');
        }
        document.getElementById('sql-output-result').value = sqlCondition;
    }

    convertFromSql() {
        const inputSql = document.getElementById('sql-reverse-input').value.trim();
        if (!inputSql) {
            alert('请输入SQL IN条件');
            return;
        }

        // 智能解析：支持多种格式
        let values = [];
        
        // 1. 提取括号内的内容（如果有括号）
        const bracketMatch = inputSql.match(/\(\s*([^)]+)\s*\)/);
        let content = bracketMatch ? bracketMatch[1] : inputSql;
        
        // 2. 清理内容：移除可能的字段名和IN关键字
        content = content.replace(/^.*IN\s+/i, '').trim();
        
        // 3. 解析值
        values = this.parseValues(content);

        if (values.length === 0) {
            alert('无法解析SQL条件中的值');
            return;
        }

        document.getElementById('sql-reverse-output').value = values.join('\n');
    }

    parseValues(content) {
        const values = [];
        
        // 清理内容
        content = content.trim();
        if (!content) return values;

        // 处理引号字符串
        const stringRegex = /'([^']*(?:''[^']*)*)'/g;
        let match;
        let lastIndex = 0;
        
        while ((match = stringRegex.exec(content)) !== null) {
            // 添加匹配到的字符串之前的非字符串值
            const beforeStr = content.substring(lastIndex, match.index).trim();
            if (beforeStr) {
                const parts = beforeStr.split(',').map(p => p.trim()).filter(p => p);
                values.push(...parts.filter(p => /^\d+(\.\d+)?$/.test(p)));
            }
            
            // 添加字符串值（处理转义的单引号）
            const strValue = match[1].replace(/''/g, "'");
            values.push(strValue);
            lastIndex = stringRegex.lastIndex;
        }
        
        // 处理剩余的逗号分隔值
        const remaining = content.substring(lastIndex).trim();
        if (remaining) {
            const parts = remaining.split(',').map(p => p.trim()).filter(p => p);
            for (const part of parts) {
                if (part.startsWith("'") && part.endsWith("'")) {
                    // 处理未匹配的引号字符串
                    values.push(part.slice(1, -1).replace(/''/g, "'"));
                } else if (/^\d+(\.\d+)?$/.test(part)) {
                    // 数字
                    values.push(part);
                } else {
                    // 其他值（去除可能的引号）
                    values.push(part.replace(/^["']|["']$/g, ''));
                }
            }
        }

        return values;
    }

    clearInputs() {
        document.getElementById('sql-input-data').value = '';
        document.getElementById('sql-output-result').value = '';
    }

    clearReverseInputs() {
        document.getElementById('sql-reverse-input').value = '';
        document.getElementById('sql-reverse-output').value = '';
    }
}

// 全局函数，供HTML调用
function convertToSql() {
    if (!window.sqlTool) {
        window.sqlTool = new SQLTool();
    }
    window.sqlTool.convertToSql();
}

function convertFromSql() {
    if (!window.sqlTool) {
        window.sqlTool = new SQLTool();
    }
    window.sqlTool.convertFromSql();
}

function clearInputs() {
    if (!window.sqlTool) {
        window.sqlTool = new SQLTool();
    }
    window.sqlTool.clearInputs();
}

function clearReverseInputs() {
    if (!window.sqlTool) {
        window.sqlTool = new SQLTool();
    }
    window.sqlTool.clearReverseInputs();
}

function copyToClipboard(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        element.select();
        document.execCommand('copy');
        
        // 显示复制成功提示
        const originalText = event.target.textContent;
        event.target.textContent = '已复制!';
        setTimeout(() => {
            event.target.textContent = originalText;
        }, 1000);
    }
}

// 初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        window.sqlTool = new SQLTool();
    });
} else {
    window.sqlTool = new SQLTool();
}